package com.zt.weibo.login;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.net.http.SslError;
import android.os.Bundle;
import android.view.View;
import android.view.Window;
import android.webkit.CookieSyncManager;
import android.webkit.SslErrorHandler;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Toast;

import com.weibo.net.AccessToken;
import com.weibo.net.DialogError;
import com.weibo.net.Utility;
import com.weibo.net.Weibo;
import com.weibo.net.WeiboDialogListener;
import com.weibo.net.WeiboException;
import com.weibo.net.WeiboParameters;
import com.zt.weibo.R;
import com.zt.weibo.WeiboApp;
import com.zt.weibo.utils.PrintLog;
import com.zt.weibo.utils.SwitchActivity;
import com.zt.weibo.utils.WeiboCons;

public class AuthorizeActivity extends Activity
{
	private WebView mWebView = null;
	private ProgressDialog mWaitDialog = null;
	private String mUrl = null;
	private String mUserName = "";
	private WeiboDialogListener mListener = null;

	@Override
	protected void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);
		PrintLog.debug("Authorize Activity On Create");
		setContentView(R.layout.login_auth);
		WeiboApp.addActivity(this);
		if (null != getIntent().getStringExtra("UserName"))
		{
			mUserName = getIntent().getStringExtra("UserName");
		}
		init();
	}

	@Override
	protected void onDestroy()
	{
		super.onDestroy();
		PrintLog.debug("Authorize Activity On Destroy");
		WeiboApp.delActivity(this);
	}
	
	private void init()
	{
		CookieSyncManager.createInstance(this);
		WeiboParameters parameters = new WeiboParameters();
		parameters.add("client_id", WeiboCons.APP_KEY);
		parameters.add("response_type", "token");
		parameters.add("redirect_uri", WeiboCons.URL_REDIRECT);
		parameters.add("display", "mobile");
		
		if (WeiboApp.mWeibo.isSessionValid())
		{
			PrintLog.debug("再次授权，传入需要刷新的access_token");
			parameters.add("access_token", WeiboApp.mWeibo.getAccessToken().getToken());
		}
		mUrl = Weibo.URL_OAUTH2_ACCESS_AUTHORIZE + "?" + Utility.encodeUrl(parameters);
		findView();
		mListener = new AuthListener(); 
	}

	private void findView()
	{
		mWebView = (WebView) findViewById(R.id.login_webview);
		mWaitDialog = new ProgressDialog(this);
		mWaitDialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
		mWaitDialog.setMessage("正在载入，请稍后...");
		mWebView.setVerticalScrollBarEnabled(false);
		mWebView.setHorizontalScrollBarEnabled(false);
		mWebView.getSettings().setJavaScriptEnabled(true);
		mWebView.setWebViewClient(new WeiboWebViewClient());
		mWebView.loadUrl(mUrl);
		mWebView.setVisibility(View.INVISIBLE);
	}
	
	private class WeiboWebViewClient extends WebViewClient
	{

		@Override
		public boolean shouldOverrideUrlLoading(WebView view, String url)
		{
			PrintLog.debug("Redirect URL: " + url);
			// 待后台增加对默认重定向地址的支持后修改下面的逻辑
			if (url.startsWith(WeiboApp.mWeibo.getRedirectUrl()))
			{
				handleRedirectUrl(view, url);
				finish();
				return true;
			}
			// launch non-dialog URLs in a full browser
			startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(url)));
			return true;
		}

		@Override
		public void onReceivedError(WebView view, int errorCode, String description,
				String failingUrl)
		{
			super.onReceivedError(view, errorCode, description, failingUrl);
			mListener.onError(new DialogError(description, errorCode, failingUrl));
			finish();
		}

		@Override
		public void onPageStarted(WebView view, String url, Bitmap favicon)
		{
			PrintLog.debug("onPageStarted URL: " + url);
			// google issue. shouldOverrideUrlLoading not executed
			if (url.startsWith(WeiboApp.mWeibo.getRedirectUrl()))
			{
				handleRedirectUrl(view, url);
				view.stopLoading();
				finish();
				return;
			}
			super.onPageStarted(view, url, favicon);
			mWaitDialog.show();
		}

		@Override
		public void onPageFinished(WebView view, String url)
		{
			PrintLog.debug("onPageFinished URL: " + url);
			super.onPageFinished(view, url);
			mWaitDialog.dismiss();
			mWebView.setVisibility(View.VISIBLE);
			mWebView.requestFocus();
		}

		@Override
		public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error)
		{
			handler.proceed();
		}

	}

	private void handleRedirectUrl(WebView view, String url)
	{
		Bundle values = Utility.parseUrl(url);

		String error = values.getString("error");
		String error_code = values.getString("error_code");

		if (error == null && error_code == null)
		{
			mListener.onComplete(values);
		}
		else if (error.equals("access_denied"))
		{
			// 用户或授权服务器拒绝授予数据访问权限
			mListener.onCancel();
		}
		else
		{
			mListener.onWeiboException(new WeiboException(error, Integer.parseInt(error_code)));
		}
	}
	
	private class AuthListener implements WeiboDialogListener
	{
		@Override
		public void onComplete(Bundle values) {
			PrintLog.debug("授权弹出框正常结束");
			CookieSyncManager.getInstance().sync();
			String token = values.getString("access_token");
			String expires_in = values.getString("remind_in");
			if(null != values.getString("refresh_token")
					&& !"".equals(values.getString("refresh_token")))
			{
				token = values.getString("refresh_token");
			}
			AccessToken accessToken = new AccessToken(token, WeiboCons.APP_KEY);
			accessToken.setExpiresIn(expires_in);
			if(WeiboApp.bIsUserExist && WeiboApp.bIsUserInvalid)
			{
				WeiboApp.mDBMgr.updateOauthInfo(mUserName, token, expires_in);
			}
			else if (!WeiboApp.bIsUserExist)
			{
				WeiboApp.mDBMgr.insertOauthInfo(mUserName, token, expires_in);
			}
			WeiboApp.mDBMgr.moveToFirst(mUserName);
			WeiboApp.mWeibo.setAccessToken(accessToken);
			SwitchActivity.weiboMain(AuthorizeActivity.this);
		}

		@Override
		public void onError(DialogError e) {
			Toast.makeText(getApplicationContext(),
					"Auth error : " + e.getMessage(), Toast.LENGTH_LONG).show();
		}

		@Override
		public void onCancel() {
			Toast.makeText(getApplicationContext(), "Auth cancel",
					Toast.LENGTH_LONG).show();
		}

		@Override
		public void onWeiboException(WeiboException e) {
			Toast.makeText(getApplicationContext(),
					"Auth exception : " + e.getMessage(), Toast.LENGTH_LONG)
					.show();
		}
	}
	
}
